/*
 * Galaxium Messenger
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Galaxium.Core
{
	public static class FileUtility
	{
		public static bool IsValidFileName (string filename)
		{
			if (filename == null || filename.Length == 0)
				return false;
			
			if (filename.Trim (' ').Length == 0)
				return false;
			
			//see: http://www.answers.com/topic/comparison-of-file-systems
			int length = Encoding.UTF8.GetByteCount (filename);
			if (length > 255)
				return false;

			if (filename.IndexOfAny (Path.GetInvalidFileNameChars ()) >= 0)
				return false;
			
			return true;
		}
		
		public static bool IsValidDirectoryName (string directory)
		{
			if (directory == null || directory.Length == 0)
				return false;
			
			if (directory.Trim (' ').Length == 0)
				return false;
			
			//see: http://www.answers.com/topic/comparison-of-file-systems
			int length = Encoding.UTF8.GetByteCount (directory);
			if (length > 255)
				return false;
			
			if (directory.IndexOfAny (Path.GetInvalidPathChars ()) >= 0)
				return false;
			
			return true;
		}
		
		public static string GetRandomFileName ()
		{
			StringBuilder builder = new StringBuilder ();
			Random random = new Random (DateTime.Now.Millisecond);
			char ch;

			for (int i = 0; i < 10; i++)
			{
				ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
				builder.Append(ch);
			}
			
			return builder.ToString();
		}
		
		public static string GetRandomFileName (string directory)
		{
			string filename = GetRandomFileName ();
			
			while (File.Exists(Path.Combine(directory, filename)))
				filename = GetRandomFileName ();
			
			return Path.Combine(directory, filename);
		}
		
		public static string GetFileChecksum (string filename)
		{
			if (!File.Exists (filename))
				return null;
			
			MD5 md = MD5.Create ();
			using (FileStream stream = File.OpenRead (filename)) {
				byte[] hash = md.ComputeHash (stream);
				return Convert.ToBase64String (hash);
			}
		}
	}
}